const express = require('express');
const jwt = require('jsonwebtoken');
require('express-async-errors');

const app = express();
const {
  User
} = require('./model');

const SECRET = 'su123$dfs54wef%a5e6W2';
app.use(express.json());


const auth = async (req, res, next) => {

  // 此处需要 try catch
  const raw = String(req.headers.authorization).split(' ').pop()
  const { id } = jwt.verify(raw, SECRET);

  req.user = await User.findById(id);

  if (!req.user) {
    return res.status(405).send('no user');
  }

  next();
}


app.get('/', async (req, res) => {
  res.send('ok');
})


app.post('/api/register', async (req, res) => {
  console.log(req.body);

  const user = await User.create({
    username: req.body.username,
    password: req.body.password
  })

  res.send(user);
})

app.post('/api/login', async (req, res) => {
  const user = await User.findOne({
    username: req.body.username
  })

  if (!user) {
    return res.status(422).send({
      message: 'not find user'
    })
  }

  const isPasswordValid = require('bcrypt').compareSync(
    req.body.password,
    user.password
  )

  if (!isPasswordValid) {
    return res.status(422).send({
      message: 'password fad'
    })
  }

  const token = jwt.sign({
    id: String(user._id),
  }, SECRET)

  res.send({
    user,
    token
  });
})


app.post('/api/profile', auth, async (req, res) => {
  res.send(req.user);
})


app.post('/api/users', async (req, res) => {
  const users = await User.find();

  res.send(users);
})


app.use((err, req, res, next) => {
  console.error('ERROR: ', err)
  res.send(err.message || 'Something broke!')
});

app.listen(3001, (err) => {

  console.log('Runing ... ')
})